package src.main.fagnwenzhe;

public class VisitorPatternDemo {
    public static void main(String[] args) {
        ComputerPart computer = new Computer();
        computer.accept(new ComputerPartDisplayVisitor());//接受访问者
    }
}

/**表述元素的接口*/
interface ComputerPart {
    public void accept(ComputerPartVisitor computerPartVisitor);
}
/**ComputerPart接口 具体实现 Keyboard*/
class Keyboard  implements ComputerPart {
    @Override
    public void accept(ComputerPartVisitor computerPartVisitor) {
        computerPartVisitor.visit(this);//访问进行操作
    }
}
/**ComputerPart接口 具体实现 Monitor*/
class Monitor  implements ComputerPart {
    @Override
    public void accept(ComputerPartVisitor computerPartVisitor) {
        computerPartVisitor.visit(this);
    }
}
/**ComputerPart接口 具体实现 Mouse*/
class Mouse  implements ComputerPart {
    @Override
    public void accept(ComputerPartVisitor computerPartVisitor) {
        computerPartVisitor.visit(this);
    }
}
/**ComputerPart接口 具体实现 Computer。此类也实现了实体访问者来执行相应的动作*/
class Computer implements ComputerPart {
    ComputerPart[] parts;
    public Computer(){//计算机组件
        parts = new ComputerPart[] {new Mouse(), new Keyboard(), new Monitor()};
    }
    /**访问者访问规则*/
    @Override //根据计算机组件遍历访问，进入每个组件实体类。
    public void accept(ComputerPartVisitor computerPartVisitor) {
        for (int i = 0; i < parts.length; i++) {
            parts[i].accept(computerPartVisitor);
        }
        computerPartVisitor.visit(this);
    }
}

/**访问者接口*/
interface ComputerPartVisitor {
    public void visit(Computer computer);
    public void visit(Mouse mouse);
    public void visit(Keyboard keyboard);
    public void visit(Monitor monitor);
}
/**具体实现的访问者*/
class ComputerPartDisplayVisitor implements ComputerPartVisitor {

    @Override
    public void visit(Computer computer) {
        System.out.println("Displaying Computer.");
    }

    @Override
    public void visit(Mouse mouse) {
        System.out.println("Displaying Mouse.");
    }

    @Override
    public void visit(Keyboard keyboard) {
        System.out.println("Displaying Keyboard.");
    }

    @Override
    public void visit(Monitor monitor) {
        System.out.println("Displaying Monitor.");
    }
}